package com.itheima.nio.tomcat.parse;

import com.itheima.nio.tomcat.domain.HttpResponse;
import com.itheima.nio.tomcat.exception.IsNotImplementsHttpServletException;
import com.itheima.nio.tomcat.inter.HttpServlet;
import com.itheima.nio.tomcat.inter.PraseServletConfig;
import com.itheima.nio.tomcat.inter.ServletConcurrentHashMap;

import java.io.FileInputStream;
import java.util.Properties;

// 解析properties文件的类
public class PropertiesPraseServletConfig implements PraseServletConfig {

    @Override
    public void parse() {

        try {

            // 1. 读取配置文件中内容,读取到一个Properties集合中
            Properties properties = new Properties() ;
            properties.load(new FileInputStream(HttpResponse.WEB_APP_PATH + "\\config\\servlet-info.properties"));

            // 2. 根据键找到对应的值
            String servletInfoValue = properties.getProperty("servlet-info");

            // 3. 解析值，获取每一部分的数据，通过反射创建对应的Servlet的对象，并将其存储到ServletConcurrentHashMap.concurrentHashMap
            String[] split = servletInfoValue.split(";");
            for(String servletInfo : split) {

                // /servlet/UserServlet,com.itheima.nio.tomcat.servlet.UserServlet
                String[] servletInfoArr = servletInfo.split(",");
                String urlPattern = servletInfoArr[0];

                // 获取Servlet的全类名，通过反射创建该类对象
                Class servletClazz = Class.forName(servletInfoArr[1]);

                // 获取该类所实现的所有的接口信息(重点)
                boolean flag = false ;                  // 定义一个标记 ， 记录当前这个类所实现的接口中是否存在HttpServlet接口
                Class[] interfaces = servletClazz.getInterfaces();
                for(Class clazz : interfaces) {
                    if(clazz == HttpServlet.class) {
                        flag = true ;
                        break;
                    }
                }

                // 判断标记
                if(flag) {

                    HttpServlet httpServlet = (HttpServlet)servletClazz.newInstance() ;

                    // 把Servlet的对应信息存储到ServletConcurrentHashMap.concurrentHashMap
                    ServletConcurrentHashMap.concurrentHashMap.put(urlPattern , httpServlet) ;
                }else {

                    try {

                        throw new IsNotImplementsHttpServletException(servletClazz.getName() + "----->>> is not implements HttpServlet interface ....") ;

                    }catch (Exception e ) {
                        e.printStackTrace();
                    }

                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }



    }

}
